//
//  SWJoinableGroupCollection.swift
//  MiU
//  SWGroupCell 集合容器
//  Created by miss on 15/12/10.
//  Copyright © 2015年 MiU. All rights reserved.
//

import Foundation
import UIKit
class SWGroupCollection: UIView,UIScrollViewDelegate
{
    weak var delegate:ClickActionDelegate?
    
    var data:[Any]?
    {
        didSet
        {
            _scrollView.removeAllSubview()
            _cells.removeAll()
            let count:Int = data?.count ?? 0
            if let data = data, data.count > 0
            {
                for i in 0..<count
                {
                    let originSize:CGSize = CGSizeMake(_originWidth, height)
                    let cell = SWGroupCell(frame: CGRectMake(_scrollView.width * CGFloat(i), 0, _scrollView.width, height), originSize: originSize)
                    cell.data = data[i]
                    _cells.append(cell)
                    _scrollView.addSubview(cell)
                }
            }
            _scrollView.contentSize = CGSizeMake(_scrollView.width * CGFloat(count), _scrollView.height)
            _index = 0
            if count > 2
            {
                _index = 1
                _scrollView.setContentOffset(CGPointMake(_scrollView.width, 0), animated: false)
            }
            scrollViewDidScroll(_scrollView)
            scrollViewDidEndDecelerating(_scrollView)
        }
    }
    
    private var _cells:[SWGroupCell] = []
    private var _index:Int = 0
    private var _originWidth:CGFloat = 0
    private var _grid:CGFloat = 0
    private let HitTestTag:Int = 10086
    
    private var _scrollView:UIScrollView = UIScrollView()
    
    init(frame: CGRect, originWidth:CGFloat, grid:CGFloat)
    {
        super.init(frame: frame)
        _originWidth = originWidth
        _grid = grid
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        let hitView:UIView = UIView()
        hitView.frame = CGRectMake(0, 0, width, height)
        hitView.tag = HitTestTag
        addSubview(hitView)
        
        let pageWidth:CGFloat = _originWidth + _grid
        let leftMargin:CGFloat = (width - pageWidth) * 0.5
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(scrollViewTapped(_:)))
        _scrollView.frame = CGRectMake(leftMargin, 0, pageWidth, height)
        _scrollView.delegate = self
        _scrollView.showsHorizontalScrollIndicator = false
        _scrollView.showsVerticalScrollIndicator = false
        _scrollView.isPagingEnabled = true
        _scrollView.clipsToBounds = false
        _scrollView.addGestureRecognizer(tapGesture)
        addSubview(_scrollView)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView)
    {
        let contentSize:CGSize = scrollView.contentSize
        let contentOffset:CGPoint = scrollView.contentOffset;
        let imageWidth:CGFloat = floor(scrollView.width)
        //print("contentOffset.x:", contentOffset.x)
        //小数点误差导致页数比实际少一页
        let index:Int = Int(ceil(contentOffset.x) / imageWidth)
        if index >= 0
        {
            _index = index
            //print("index:", index)
        }
        
        //中间大两边小的效果
        let count:Int = _cells.count
        if index >= 0 && index < count && _index >= 0 && _index < count && contentOffset.x >= 0 && contentOffset.x <= contentSize.width - imageWidth
        {
            let removedCover:SWGroupCell = _cells[_index]
            //左边
            let leftImageView:SWGroupCell? = _cells.valueAt(_index - 1)
            
            //左左边
            let leftImageView2:SWGroupCell? = _cells.valueAt(_index - 2)
            //右边
            let rightImageView:SWGroupCell? = _cells.valueAt(_index + 1)
            //右右边
            let rightImageView2:SWGroupCell? = _cells.valueAt(_index + 2)
            
            //当前显示的这张高度为1：1，旁边两张为最小为0.8
            let minScale:CGFloat = SWGroupCell.MinScale
            var scale:CGFloat = (imageWidth - abs(contentOffset.x - imageWidth * CGFloat(_index))) / imageWidth
            scale = minScale + (scale * (1 - minScale))
            removedCover.scale = scale
            
            
            if leftImageView != nil
            {
                scale = (imageWidth - abs(contentOffset.x - imageWidth * CGFloat(_index - 1))) / imageWidth
                scale = minScale + (scale * (1 - minScale))
                leftImageView?.scale = scale
            }
            if leftImageView2 != nil
            {
                scale = (imageWidth - abs(contentOffset.x - imageWidth * CGFloat(_index - 2))) / imageWidth
                scale = minScale + (scale * (1 - minScale))
                leftImageView2?.scale = scale
            }
            if rightImageView != nil
            {
                scale = (imageWidth - abs(contentOffset.x - imageWidth * CGFloat(_index + 1))) / imageWidth
                scale = minScale + (scale * (1 - minScale))
                rightImageView?.scale = scale
            }
            if rightImageView2 != nil
            {
                scale = (imageWidth - abs(contentOffset.x - imageWidth * CGFloat(_index + 2))) / imageWidth
                scale = minScale + (scale * (1 - minScale))
                rightImageView2?.scale = scale
            }
        }
        
    }
    
    //停止滚动后
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
    {
        let contentSize:CGSize = scrollView.contentSize
        let contentOffset:CGPoint = scrollView.contentOffset
        let imageWidth:CGFloat = floor(scrollView.width)
        let count:Int = _cells.count
        if _index >= 0 && _index < count && _index >= 0 && _index < count && contentOffset.x >= 0 && contentOffset.x <= contentSize.width - imageWidth
        {
            let middleCell:SWGroupCell? = _cells[_index]
            let leftCell:SWGroupCell? = _cells.valueAt(_index - 1)
            let rightCell:SWGroupCell? = _cells.valueAt(_index + 1)
            middleCell?.focus = true
            leftCell?.focus = false
            rightCell?.focus = false
        }
    }
    
    @objc private func scrollViewTapped(_ gesture:UITapGestureRecognizer)
    {
        let point = gesture.location(in: _scrollView.superview)
        if point.x < _scrollView.x && _index > 0
        {
            delegate?.view(self, click: CallbackAction.Tap, argument: ["index":_index - 1])
        }
        else if point.x > _scrollView.right && _index < _cells.count - 1
        {
            delegate?.view(self, click: CallbackAction.Tap, argument: ["index":_index + 1])
        }
        else if point.x > _scrollView.x && point.x < _scrollView.right
        {
            delegate?.view(self, click: CallbackAction.Tap, argument: ["index":_index])
        }
    }
    
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?
    {
        //将所有scrollView以外的手势重定向给scrollView，以便在scrollView区域外也可滑动和点击
        let hitView:UIView? = super.hitTest(point, with: event)
        if hitView?.tag == HitTestTag
        {
            return _scrollView
        }
        return hitView
    }
    
    
    
    
    
    
}
